package util;

import java.io.PrintWriter;

/**
 * XMLWriter is a class used to easily output XML.
 *  
 * @author Andrew Trusty
 */
public class XMLWriter {
	private static final int tabsize = 2;

	/**
	 * Number of spaces indentation currently being used.
	 */
	private int spaces;
	/**
	 * The PrintWriter used to output the XML.
	 */
	private PrintWriter writer;
	
	/**
	 * XMLWriter constructor.
	 *  
	 * @param w PrintWriter to use for XML output.
	 */
	public XMLWriter(PrintWriter w) {
		writer = w;
		spaces = 0;
	}	
	/**
	 * Reset the number of spaces being used for indentation.
	 */
	public void resetTab() {
		spaces = 0;
	}
	/**
	 * Increase the indentation by the tabsize.
	 */
	private void tab() {
		spaces += tabsize;
	}
	/**
	 * Decrease the indentation by the tabsize.
	 */
	private void untab() {
		spaces -= tabsize;
	}
	/**
	 * Write out indentation.
	 */
	private void indent() {
		for (int i = 0; i < spaces; ++i) writer.print(" ");
	}
	/**
	 * Set the number of tabs to use.
	 * @param t the number of tabs
	 */
	public void setTab(int t) {
		if (t >= 0)	spaces += t * tabsize;
	}
	
	/**
	 * Public XML writing methods.
	 */	
	public void tag(String tagname, String value) {
		indent();
		writer.print("<"+tagname+">"+value+"</"+tagname+">\n");
	}
	public void tag(String tagname, int value) {
		tag(tagname, ""+value);
	}
	public void tag(String tagname, long value) {
		tag(tagname, ""+value);
	}
	public void tag(String tagname, double value) {
		tag(tagname, ""+value);
	}
	/**
	 * Writes an opening or closing tag and increased or decreases the 
	 * indentation depending on if it is an opening or closing tag.
	 * 
	 * @param tagname the tag to write, a closing tag should start with '/'
	 */
	public void tag(String tagname) {
		if (tagname.charAt(0) == '/') untab();
		indent();
		writer.print("<"+tagname+">\n");
		if (tagname.charAt(0) != '/') tab();
	}
	/**
	 * Writes the given string assuming it is raw XML.  Appends a newline.
	 * 
	 * @param xml string to write
	 */
	public void rawXML(String xml) {
		indent();
		writer.print(xml + "\n");
	}
	/**
	 * Close the PrintWriter used to output the XML. 
	 */
	public void close() {
		writer.close();
	}
}
